//
//  SetPredictViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2016/12/11.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "SetPredictViewController.h"
#import "DatePickerView.h"
#import "MoneyPicker.h"
#import "SelectIconView.h"
#import "PredictBackImageCell.h"
#import "PredictSelectedCell.h"
#import "PredictNormalCell.h"

@interface SetPredictViewController ()<UITextFieldDelegate,SelectIconViewDelegate,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
typedef NS_ENUM(NSInteger, TFTag){
    TFTagA = 0,//日期
    TFTagB, //开始时间
    TFTagC,  //结束时间
    TFTagD //输入金额
};
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString *date;
@property (nonatomic, copy) NSString *time;
@property (nonatomic, copy) NSString *money;

@property (nonatomic, strong) DatePickerView *datePickerView;
@property (nonatomic, strong) DatePickerView *timePickerView;
@property (nonatomic, strong) SelectIconView *selectView;

@property (nonatomic, strong) NSArray *moneyArray;
@property (nonatomic, strong) MoneyPicker *moneyPicker;
@property (nonatomic, strong) UIPickerView *pickerView;
/**
   signRedPaper:记录发送红包 signPresetnt 记录发送礼物
 */
@property (nonatomic, assign) BOOL signRedPaper;
@property (nonatomic, assign) BOOL signPresent;
/**
 判断当前是否可以选择价格 1: 可以  0:否
 */
@property (nonatomic, copy) NSString *is_Edit;
/**
 当前限定价格
 */
@property (nonatomic, copy) NSString *price;

/**
  封面
 */
@property (nonatomic, strong) UIImage *backImg;
//封面名称 路径
@property (nonatomic, copy) NSString *imageFile;
@property (nonatomic, copy) NSString *imagePath;
@end

@implementation SetPredictViewController
#pragma mark -- 进入创建预播(查询价格能否修改)
- (void)EnterCreatLivingRequest {
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:KEnterCreatLiving];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            self.is_Edit = KString(responseObject[@"data"][@"edit"]);
            self.price = KString(responseObject[@"data"][@"s_price"]);
            [self.tableView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

//上传封面
- (void)uploadImageRequestWithImage:(UIImage *)image {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kUploadImage];
    QZHUploadFormData *uploadData = [[QZHUploadFormData alloc] init];
    uploadData.imageData = UIImageJPEGRepresentation(image, 0.5);
    uploadData.dataType = DataTypeJpeg;
    uploadData.name = @"img";
    uploadData.fileName = @"image.jpg";
    [self showHUDInView:self.view title:@"上传封面中"];
    [NetworkTools UploadRequestWithParams:dict UrlString:urlString uploadParams:uploadData successBlock:^(id responseObject) {
        [self hideHUD];
        if ([responseObject[@"code"] intValue] == 200) {
            [self.tableView reloadData];
            self.imageFile = responseObject[@"data"][@"file"];
            self.imagePath = responseObject[@"data"][@"path"];
        }
    } failureBlock:^(NSError *error) {
        [self hideHUD];
    } showHUD:NO];
}

#pragma mark -- 创建预播网络请求
- (void)creatPredictLiveRequest {
    NSString *date = self.date;
    NSString *time = self.time;
    NSString *price = self.money;
    NSString *gift ;
    NSString *Redpack;
    if (self.signPresent) {
        gift = @"10";
    } else {
        gift = @"0";
    }
    if (self.signRedPaper) {
        Redpack = @"10";
    } else {
        Redpack = @"0";
    }
    if ([self.is_Edit isEqualToString:@"0"]) {
        price = self.price;
    } else {
        price = self.money;
    }
    if (!self.imageFile) {
        self.imageFile = @"";
    }
    if (!self.imagePath) {
        self.imagePath = @"";
    }
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN,
                           @"date":date,
                           @"star":time,
                           @"end":@"0",
                           @"price":price,
                           @"gift":gift,
                           @"package":Redpack,
                           @"path":self.imagePath,
                           @"file":self.imageFile
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kPredict];
    [self showHUDInView:self.view title:@"发布中..."];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [self hideHUD];
        [[NSNotificationCenter defaultCenter] postNotificationName:kStarHomeNotifica object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    } failureBlock:^(NSError *error) {
        [self hideHUD];
    } showHUD:NO];
}

- (void)viewWillAppear:(BOOL)animated {

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"预播设定";
    [self setUpUI];
    [self setNav];
}



#pragma mark -- UI
- (void)setUpUI {
    [self EnterCreatLivingRequest];
    [self creatTableView];
    if ([self.is_Edit isEqualToString:@"0"]) {
        self.money = self.price;
    } else {
        self.money = @"0";
    }
    //设置发送红包和礼物初始为NO
    self.signPresent = NO;
    self.signRedPaper = NO;
    
}

- (void)setNav {
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [rightBtn setTitle:@"发布" forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(PublishClick:) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.titleLabel.font = UIFont(14);
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = item;
}
#pragma mark -- 发布
- (void)PublishClick:(id)sender {
    NSString *date = self.date;
    if (!date.length) {
        [self showTitle:@"请选择预播日期!"];
        return;
    }
    NSString *time = self.time;
    if (!time.length) {
        [self showTitle:@"请选择预播开始时间!"];
        return;
    }
    NSString *price = self.money;
    if (!price.length) {
        [self showTitle:@"请选择观看价格!"];
    }
    [self creatPredictLiveRequest];
}

- (void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 30)];
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.font = UIFont(12);
    tipLabel.textColor = [UIColor redColor];
    tipLabel.text = @"注 : 价格设定后一个月内不可以修改";
    [bottomView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomView.mas_left).offset(15);
        make.centerX.equalTo(bottomView.mas_centerX);
    }];
    self.tableView.tableFooterView = bottomView;
    [self.view addSubview:self.tableView];
}

#pragma mark -- tableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        PredictBackImageCell *cell = [PredictBackImageCell loadNibCellWithTabelView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleLabel.text = @"封面";
        if (self.backImg) {
            cell.backImgView.image = self.backImg;
        }
        return cell;
    } else if (indexPath.row == 1||indexPath.row == 2) {
        PredictSelectedCell *cell = [PredictSelectedCell loadNibCellWithTabelView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 1) {
            cell.titleLabel.text = @"发红包";
        } else {
            cell.titleLabel.text = @"送礼品";
        }
        return cell;
    }
    PredictNormalCell *cell = [PredictNormalCell loadNibCellWithTabelView:tableView];
    switch (indexPath.row) {
        case 3:
            cell.titleLabel.text = @"开播日期";
            break;
        case 4:
            cell.titleLabel.text = @"开播时间";
            break;
        case 5:
            cell.titleLabel.text = @"观看价格";
            cell.descLabel.text = self.price;
            break;
            
        default:
            break;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) WeakSelf = self;
    switch (indexPath.row) {
        case 0:{//设置封面
            [self setBackImgView];
        }
            break;
        case 1:{//有红包
            self.signRedPaper = !self.signRedPaper;
            PredictSelectedCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            if (self.signRedPaper) {
                cell.selectImgView.image = kSET_IMAGE(@"select_selected");
            } else {
                cell.selectImgView.image = kSET_IMAGE(@"select_normal");
            }
        }
            break;
        case 2:{//有礼品
            self.signPresent = !self.signPresent;
            PredictSelectedCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            if (self.signPresent) {
                cell.selectImgView.image = kSET_IMAGE(@"select_selected");
            } else {
                cell.selectImgView.image = kSET_IMAGE(@"select_normal");
            }
        }
            break;
        case 3:{//开播日期
            PredictNormalCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            if (!self.datePickerView) {
                self.datePickerView  = [[DatePickerView alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT - 300, kSCREEN_WIDTH, 260) DateMode:UIDatePickerModeDate];
            }
            [self.view addSubview:self.datePickerView];
            self.datePickerView.DateSelected = ^(NSString *state){
                if ([state isEqualToString:@"取消"]) {
                    [WeakSelf.datePickerView removeFromSuperview];
                } else {//完成
                    [WeakSelf.datePickerView removeFromSuperview];
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    [formatter setDateFormat:@"YYYY-MM-dd"];
                    cell.descLabel.text = [formatter stringFromDate:WeakSelf.datePickerView.datePicker.date];
                    WeakSelf.date = [formatter stringFromDate:WeakSelf.datePickerView.datePicker.date];
                }
            };
        }
            break;
        case 4:{//开播时间
            PredictNormalCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            if (!self.timePickerView) {
                self.timePickerView  = [[DatePickerView alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT - 300, kSCREEN_WIDTH, 260) DateMode:UIDatePickerModeTime];
            }
            [self.view addSubview:self.timePickerView];
            self.timePickerView.DateSelected = ^(NSString *state){
                if ([state isEqualToString:@"取消"]) {
                    [WeakSelf.timePickerView removeFromSuperview];
                } else {//完成
                    [WeakSelf.timePickerView removeFromSuperview];
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    [formatter setDateFormat:@"HH:mm"];
                    cell.descLabel.text = [formatter stringFromDate:WeakSelf.timePickerView.datePicker.date];
                    WeakSelf.time = [formatter stringFromDate:WeakSelf.timePickerView.datePicker.date];
                }
            };
        }
            break;
        case 5:{//价格
            if ([self.is_Edit intValue]) {//可以修改
                PredictNormalCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                if (!self.moneyPicker) {
                    self.moneyPicker = [[MoneyPicker alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT - 300, kSCREEN_WIDTH, 260)];
                    self.moneyPicker.backgroundColor = [UIColor whiteColor];
                }
                [self.view addSubview:self.moneyPicker];
                self.moneyPicker.DateSelected = ^(NSString *state){
                    if ([state isEqualToString:@"取消"]) {
                        [WeakSelf.moneyPicker removeFromSuperview];
                    } else {//完成
                        [WeakSelf.moneyPicker removeFromSuperview];
                        NSInteger row=[WeakSelf.moneyPicker.pickerView selectedRowInComponent:0];
                        cell.descLabel.text = [NSString stringWithFormat:@"%@元",[WeakSelf.moneyPicker.moneyArray objectAtIndex:row]];
                    }
                };
            } else {
                [self showTitle:@"价格修改时间未超过一个月,暂不可修改"];
            }
        }
            break;
            
        default:
            break;
    }
}

#pragma mark -- 区头视图

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 80;
    }
    return 60;
}



#pragma mark -- UITextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [self.view endEditing:YES];
    switch (textField.tag - 2000) {
        case TFTagA:

            break;
        case TFTagB:
            if (!self.timePickerView) {
                self.timePickerView  = [[DatePickerView alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT - 300, kSCREEN_WIDTH, 260) DateMode:UIDatePickerModeTime];
            }
            [self.view addSubview:self.timePickerView];
            break;
        case TFTagC:
            if (!self.timePickerView) {
                self.timePickerView  = [[DatePickerView alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT - 300, kSCREEN_WIDTH, 260) DateMode:UIDatePickerModeTime];
            }
            [self.view addSubview:self.timePickerView];
            break;
        case TFTagD:
            if (!self.moneyPicker) {
                self.moneyPicker = [[MoneyPicker alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT - 300, kSCREEN_WIDTH, 260)];
                self.moneyPicker.backgroundColor = [UIColor whiteColor];
            }
            [self.view addSubview:self.moneyPicker];
            break;

        default:
            break;
    }
    
    __weak typeof(self) WeakSelf = self;
    self.datePickerView.DateSelected = ^(NSString *state){
        if ([state isEqualToString:@"取消"]) {
            [WeakSelf.datePickerView removeFromSuperview];
        } else {//完成
            [WeakSelf.datePickerView removeFromSuperview];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"YYYY-MM-dd"];
            textField.text = [formatter stringFromDate:WeakSelf.datePickerView.datePicker.date];
        }
    };
    
    self.timePickerView.DateSelected = ^(NSString *state){
        if ([state isEqualToString:@"取消"]) {
            [WeakSelf.timePickerView removeFromSuperview];
        } else {//完成
            [WeakSelf.timePickerView removeFromSuperview];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"HH:mm"];
            textField.text = [formatter stringFromDate:WeakSelf.timePickerView.datePicker.date];
        }
    };
    self.moneyPicker.DateSelected = ^(NSString *state){
        if ([state isEqualToString:@"取消"]) {
            [WeakSelf.moneyPicker removeFromSuperview];
        } else {//完成
            [WeakSelf.moneyPicker removeFromSuperview];
            NSInteger row=[WeakSelf.moneyPicker.pickerView selectedRowInComponent:0];
            textField.text =[WeakSelf.moneyPicker.moneyArray objectAtIndex:row];
            
        }
    };
    

    return NO;
}


#pragma mark -- SelectIconView

- (void)BackImageTip:(UITapGestureRecognizer *)tap {
    if (!self.selectView) {
        self.selectView = [[NSBundle mainBundle] loadNibNamed:@"SelectIconView" owner:self options:nil].lastObject;
        self.selectView.frame = CGRectMake(0,self.view.bounds.size.height - 330, kSCREEN_WIDTH, 330);
        self.selectView.delegate = self;
        [self.selectView.bkImg sd_setImageWithURL:[NSURL URLWithString:[LSUserInfoManager sharedManager].currentUserInfo.u_avatar] placeholderImage:kPlACE_ICON];
    }
    [self.view addSubview:self.selectView];
}

- (void)close {
    [self.selectView removeFromSuperview];
}

#pragma mark -- 图片选择代理方法

//设置封面
- (void)setBackImgView {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"选择照片方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        
    }];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        /**
         其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
         */
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式:通过相机
        PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
        PickerImage.allowsEditing = YES;
        PickerImage.delegate = self;
        [self presentViewController:PickerImage animated:YES completion:nil];
    }];
    
    UIAlertAction *photos = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
        //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
        //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
        PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //允许编辑，即放大裁剪
        PickerImage.allowsEditing = YES;
        //自代理
        PickerImage.delegate = self;
        //页面跳转
        [self presentViewController:PickerImage animated:YES completion:nil];
    }];
    [alertVc addAction:camera];
    [alertVc addAction:photos];
    [alertVc addAction:cancle];
    [self presentViewController:alertVc animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *IconImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    self.backImg = IconImage;
    [self uploadImageRequestWithImage:IconImage];
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
